package com.maserb.monitor.remote;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.util.ArrayUtil;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class SchoolRecordRequestEntity {
    private String deviceId;
    private String cardId;
    private String studentId;
    /**
     * 签到时间(YYYYMMDDHHMISS)
     */
    private String startTime;
    private String optType;

    public byte[] getBytes() {
        byte[] deviceData = MessageByteUtils.fromString(deviceId, 18);
        byte[] cardData = MessageByteUtils.fromString(cardId, 18);
        byte[] studentData = MessageByteUtils.fromString(studentId, 18);
        byte[] timeData = MessageByteUtils.fromString(startTime, 14);
        byte[] optTypeData = MessageByteUtils.fromString(optType, 1);

        byte[][] datas = new byte[][]{deviceData, cardData, studentData, timeData, optTypeData};
        int totalLength = 0;
        for (int i = 0; i < datas.length; i++) {
            totalLength += datas[i].length;
        }
        byte[] result = new byte[totalLength];
        int index = 0;
        for (int i = 0; i < datas.length; i++) {
            ArrayUtil.arraycopy(datas[i], 0, result, index, datas[i].length);
            index += datas[i].length;
        }

        return result;
    }

    public void fromBytes(byte[] data) {
        int index = 0;
        int length = 18;

        byte[] deviceData = ArrayUtils.subarray(data, index, index + length);

        index += length;
        byte[] cardData = ArrayUtils.subarray(data, index, index + length);

        index += length;
        byte[] studentData = ArrayUtils.subarray(data, index, index + length);
        index += length;

        length = 14;
        byte[] timeData = ArrayUtils.subarray(data, index, index + length);
        index += length;

        length = 1;
        byte[] optTypeData = ArrayUtils.subarray(data, index, index + length);
        index += length;

        this.setDeviceId(MessageByteUtils.getString(deviceData));
        this.setCardId(MessageByteUtils.getString(cardData));
        this.setStudentId(MessageByteUtils.getString(studentData));
        this.setStartTime(MessageByteUtils.getString(timeData));
        this.setOptType(MessageByteUtils.getString(optTypeData));
    }
}
